import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { message } from 'ant-design-vue';

import { Apis } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

function processRouters(routers, parentPath = ''): any {
  const processedRouters = []; // 新建一个数组用于存储处理后的路由

  routers.forEach((router) => {
    if (!router.meta) {
      router.meta = {};
    }

    if (router.component === 'Layout' || !router.component) {
      router.component = 'BasicLayout';
    }

    // 检查 path 是否包含 http://
    if (router.path.includes('http://')) {
      router.path = ''; // 将 path 设置为空字符串
      router.meta.link = router.path; // 将 link 设置为 path
    } else if (!router.path.startsWith('/')) {
      // 如果子级的 path 没有以 / 开头，则拼接父级的 path
      router.path = `${parentPath}/${router.path}`;
    }

    // 递归处理子路由
    if (router.children) {
      router.children = processRouters(router.children, router.path); // 递归调用并更新子路由
    }

    processedRouters.push(router); // 将处理后的路由推入新数组
  });

  return processedRouters; // 返回处理后的路由数组
}

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };

  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      message.loading({
        content: `${$t('common.loadingMenu')}...`,
        duration: 1.5,
      });

      const routers = await Apis.get_getRouters();
      const transfRouters = processRouters(routers.list);
      console.log(JSON.parse(JSON.stringify(transfRouters)));

      transfRouters.unshift({
        component: 'BasicLayout',
        meta: {
          icon: 'lucide:layout-dashboard',
          order: -1,
          title: '首页',
        },
        name: 'Dashboard',
        path: '/analytics',
        children: [
          {
            name: 'analytics',
            path: '/analytics',
            component: '/dashboard/home/index.vue',
            meta: {
              affixTab: true,
              hideInMenu: true,
              icon: 'lucide:area-chart',
              title: '首页',
            },
          },
          // {
          //   name: 'Analytics',
          //   path: '/analytics',
          //   component: () => import('#/views/dashboard/analytics/index.vue'),
          //   meta: {
          //     affixTab: true,
          //     icon: 'lucide:area-chart',
          //     title: $t('page.dashboard.analytics'),
          //   },
          // },
          // {
          //   name: 'Workspace',
          //   path: '/workspace',
          //   component: () => import('#/views/dashboard/workspace/index.vue'),
          //   meta: {
          //     title: $t('page.dashboard.workspace'),
          //   },
          // },
        ],
      });

      return transfRouters;
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
